package ca.jerg.data;

import java.io.*;

public class ErgFile implements IErgFile
{
	public static void main( String args[] )
	{
		ErgFile ef = new ErgFile();
		ef.read("at-test.erg");
		ef.write();
		ef.write("dave.erg");
	}
	
	public ErgFile()
	{
		header = new ErgFileHeader();
		data = new ErgFileData();
	}
	
	public ErgFile( String version, String units, String description, String fileName )
	{
		header = new ErgFileHeader(version,units,description,fileName);
		data = new ErgFileData();
	}
	
	public void setData( ErgData data )
	{
		this.data.setData(data);
	}
	
	public ErgData getData()
	{
		return data.getData();
	}
	
	public void setFileName( String name )
	{
		header.setFileName(name);
	}
	
	public String getFileName()
	{
		return header.getFileName();
	}
	
	public void setUnits( String units )
	{
		header.setUnits(units);
	}
	
	public String getUnits()
	{
		return header.getUnits();
	}
	
	public void setVersion( String version )
	{
		header.setVersion(version);
	}
	
	public String getVersion()
	{
		return header.getVersion();
	}
	
	public void setDescription( String description )
	{
		header.setDescription(description);
	}
	
	public String getDescription()
	{
		return header.getDescription();
	}
	
	//@Override
	public int read( String fileName )
	{
		try
		{
			BufferedReader br = new BufferedReader(new FileReader(fileName));
						
			if ( header.read(br) != 0 )
			{
				System.err.println(ERG_FILE_STR + "Header read failed");
				return 2;
			}
			
			br.readLine();
			
			if ( data.read(br) != 0 )
			{
				System.err.println(ERG_FILE_STR + "Data read failed");
				return 3;
			}
		}
		catch ( FileNotFoundException fnfe )
		{
			System.err.println(ERG_FILE_STR + "File not found");
			return 1;
		}
		catch ( IOException ioe )
		{
			System.err.println(ERG_FILE_STR + "General read error");
			return 1;
		}
		
		return 0;
	}

	//@Override
	public void write()
	{
		header.write();
		data.write();
	}

	//@Override
	public boolean write( String fileName )
	{
		try
		{
			BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
			
			header.setFileName(fileName);
			if ( header.write(bw) == false )
			{
				System.err.println(ERG_FILE_STR + "Header write failed");
				return false;
			}
			
			if ( data.write(bw) == false )
			{
				System.err.println(ERG_FILE_STR + "Data write failed");
				return false;
			}
			
			bw.close();
		}
		catch ( IOException ioe )
		{
			System.err.println(ERG_FILE_STR + "General write error");
			return false;
		}
		
		return true;
	}

	private final String ERG_FILE_STR = "ErgFile: ";	
	private ErgFileHeader header;
	private ErgFileData data;
}
